//
//  MainTabBar.swift
//  SinaWeiBo
//
//  Created by 谭淇 on 15/3/5.
//  Copyright (c) 2015年 &#35885;&#28103;. All rights reserved.
//

import UIKit

class MainTabBar: UITabBar {

    // 点击加号按钮的回调(闭包)
    var compose: (()->())?
    
    override func awakeFromNib() {
        self.addSubview(composeBtn!)
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        setButtonsFrame()
    }
    
    // 调整按钮的位置
    func setButtonsFrame() {
        // 1.计算基本属性
        let tabbarButtonW = self.width / CGFloat(buttonCount)
        let h = self.height
        
        // 2.遍历子视图
        // UITabBarButton属于私有API，在程序中使用私有API，通常不能上架
        var index = 0
        for view in self.subviews as! [UIView] {
            // 判断子视图是否UITabBarButton控件(UITabBarButton继承自UIControl, 除加号按钮)
            if (view is UIControl) && !(view is UIButton) {
                view.width = tabbarButtonW
                view.x = tabbarButtonW * CGFloat(index)
                if ++index == 2 {
                    index++
                }
            }
        }
        
        // 3.设置加号按钮的位置
        composeBtn!.width = tabbarButtonW
        composeBtn!.height = self.height
        composeBtn!.centerX = self.centerX
        composeBtn!.centerY = self.centerY
    }
    
    // 加号按钮
    lazy var composeBtn: UIButton? = {
        let btn = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton
        btn.backgroundColor = UIColor.redColor()
        btn.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: .Normal)
        btn.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: .Highlighted)
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: .Normal)
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: .Highlighted)
        
        btn.addTarget(self, action: "composeClick", forControlEvents: .TouchUpInside)
        
        return btn
    }()
    
    // 加号按钮点击事件
    func composeClick() {
        if compose != nil {
            compose!()
        }
    }
    
    // 按钮总数
    let buttonCount = 5
    
}
